import 'package:flutter/material.dart';

class TestTopleftScale extends StatefulWidget {
  @override
  _TestTopleftScaleState createState() => _TestTopleftScaleState();
}

class _TestTopleftScaleState extends State<TestTopleftScale> {
  double _scale = 1.0;
  Offset _offset = Offset.zero;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onScaleUpdate: (details) {
        setState(() {
          _scale = details.scale;
          // 计算左上角在缩放后的位置，使其保持不变
          _offset = details.localFocalPoint - details.localFocalPoint * _scale;
        });
      },
      child: CustomPaint(
        size: Size(200, 200),
        painter: ZoomableCanvasPainter(scale: _scale, offset: _offset),
      ),
    );
  }
}

class ZoomableCanvasPainter extends CustomPainter {
  final double scale;
  final Offset offset;

  ZoomableCanvasPainter({required this.scale, required this.offset});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();
    canvas.translate(offset.dx, offset.dy); // 平移以保持左上角固定
    canvas.scale(scale); // 缩放

    // 绘制内容，这里只是一个简单的矩形示例
    Paint paint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawRect(Rect.fromLTWH(0, 0, 100, 100), paint);

    canvas.restore();
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
